package com.qf.core.enums;

import com.qf.core.exception.BaseException;
import com.qf.core.response.ResponseCode;

import java.util.Objects;

/**
 * @author valarchie
 */
public class BasicEnumUtil {

    private BasicEnumUtil() {}

    public static final String UNKNOWN = "未知";

    public static <E extends Enum<E> & BasicEnum<V>, V> E fromValueSafely(Class<E> enumClass, V value) {
        for (E enumConstant : enumClass.getEnumConstants()) {
            if (Objects.equals(enumConstant.getValue(), value)) {
                return enumConstant;
            }
        }
        return null;
    }

    public static <E extends Enum<E> & BasicEnum<V>, V> E fromValue(Class<E> enumClass, V value) {
        for (E enumConstant : enumClass.getEnumConstants()) {
            if (Objects.equals(enumConstant.getValue(), value)) {
                return enumConstant;
            }
        }
        throw new BaseException(ResponseCode.GET_ENUM_FAILED);
    }

    public static <E extends Enum<E> & BasicEnum<V>, V> String getDescriptionByValue(Class<E> enumClass, V value) {
        E enumConstant = fromValueSafely(enumClass, value);
        return enumConstant != null ? enumConstant.description() : UNKNOWN;
    }

    public static <E extends Enum<E> & CssTagEnum<V>, V> String getCssTagByValue(Class<E> enumClass, V value) {
        E enumConstant = fromValueSafely(enumClass, value);
        return enumConstant != null ? enumConstant.cssTag() : UNKNOWN;
    }
}

